/**
 * Created by 1 on 2016/12/29.
 */
(function (document) {
    "use strict";
    var gameInst;
    //返回数组型对象
    var $;
    var jQuery = $ = function (selector) {
        return new jQuery.fn.init(selector);
    };
    //处理数组型对象
    jQuery.fn = {
        init: function (selector) {
            var elements = document.querySelector(selector);
            Array.prototype.push.call(this, elements);
        }
    };
    jQuery.fn.init.prototype = jQuery.fn;
    //实现继承
    jQuery.extend = jQuery.fn.extend = function () {
        for (var i in arguments[0]) {
            this[i] = arguments[0][i];
        }
    };
    //添加静态方法
    jQuery.extend({
        StartGame: function () {
            window.ResourceManager.onResourceLoaded = function () {
                gameInst = new Tetris();
                gameInst.startGame();
                gameInst._initAudio();
            };
            window.ResourceManager._init();
        }
    });
    //添加实例方法
    jQuery.fn.extend({
        get: function () {
            return this[0];
        },
        css: function () {
            this.get().style[arguments[0]] = arguments[1];
        },
        on: function (eventName, eventHandler) {
            this.get().addEventListener(eventName, eventHandler, false);
        }

    });
    //调用方法
    document.addEventListener("DOMContentLoaded", function () {
        $("#btn-start").on("click", function () {
            $("div.start-container").css("display", "none");
            $("div.game-container").css("display", "block");
            $.StartGame();
        });
        $("#btn-setting").on("click", function () {
            $(".modal-dialog").css("display", "block");
        });
        $("#btn_game_pause").on("click", function (event) {
            var element = event.target;
            if (element.innerText === "暂停") {
                gameInst.pause();
                element.innerText = "继续";
            } else {
                gameInst.resume();
                element.innerText = "暂停";
            }
        });
        /* 当用于 select 元素时，change 事件会在选择某个选项时发生。
         当用于 text field 或 textarea 时，该事件会在元素失去焦点时发生*/
        $("#ck-sound").on("change", function () {
            //checked 属性设置或返回 checkbox 是否应被选中
            var enable = $("#ck-sound").get().checked;
            window.TetrisConfig.enable = enable;
        });
        $("#btn-dialog-close").on("click", function () {
            $(".modal-dialog").css("display", "none");
            if (window.state === "playing") {
                gameInst.resume();
            }
        });
        $("#btn-game-setting").on("click", function () {
            $(".modal-dialog").css("display", "block");
            window.state = gameInst._state;
            gameInst.pause();
        });
    })
})(document);